package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/lab-online/internal/user/constant"
	"github.com/lab-online/internal/user/valueobject"
	"github.com/lab-online/pkg/auth"
	mw "github.com/lab-online/pkg/middleware"
	"github.com/lab-online/pkg/resp"
)

type updatePwdReqParams struct {
	Username string `uri:"id" binding:"required" example:"20240126"` // 学号或者工号
}

type UpdatePwdReqBody struct {
	OldPassword string `json:"oldPassword" binding:"omitempty,max=64,min=8" example:"12345678"` // 旧密码
	NewPassword string `json:"newPassword" binding:"required,max=64,min=8" example:"12345678"`  //新密码
}

var UpdatePwdValidator = mw.NewValidator(func() *mw.ValidatorOptions {
	return &mw.ValidatorOptions{
		Body:   &UpdatePwdReqBody{},
		Params: &updatePwdReqParams{},
	}
})

// UpdatePassword
//
//	@Summary				修改密码
//	@Description			可以修改自己的密码,修改自己的密码需要旧密码
//	@Description			管理员可以修改任意用户的密码, 不需要旧密码
//	@Description			老师可以修改 `role` 仅为 `student` 的用户密码, 不需要旧密码
//	@Description.markdown	UpdatePassword
//	@Tags					user
//	@Accept					json
//	@Produce				json
//	@Param					Authorization	header		string				true	"Bearer Token, `All`"
//	@Param					id				path		string				true	"学号或者工号"
//	@Param					Body			body		UpdatePwdReqBody	true	"JSON 请求体"
//	@Success				200				{object}	resp.BaseRespBody
//	@Failure				400				{object}	resp.FailedRespBodyString
//	@Security				bearer
//	@x-apifox-status		"testing"
//	@Router					/v1/users/:id/password [patch]
func (h *Handler) UpdatePassword(c *gin.Context) {
	authEntity := c.MustGet(auth.KeyAuth).(auth.AuthEntity)
	params := c.MustGet(mw.KeyParams).(*updatePwdReqParams)
	body := c.MustGet(mw.KeyBody).(*UpdatePwdReqBody)

	passwordPatch := &valueobject.PasswordPatch{
		Username:    params.Username,
		OldPassword: body.OldPassword,
		NewPassword: body.NewPassword,
	}

	if err := h.domain.UpdatePassword(authEntity, passwordPatch); err != nil {
		resp.ErrorHandler(c, err)
	} else {
		resp.Success[any](c, constant.CodeSuccessUpdate)
	}
}
